package com.bdit.ydcb.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bdit.ydcb.R;
import com.bdit.ydcb.adapter.AreaTaskAdapter;
import com.bdit.ydcb.callback.JsonCallback;
import com.bdit.ydcb.model.AreaTask;
import com.bdit.ydcb.model.Page;
import com.bdit.ydcb.utils.Urls;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.wuxiaolong.pullloadmorerecyclerview.PullLoadMoreRecyclerView;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

public class AreaTaskActivity extends Activity implements PullLoadMoreRecyclerView.PullLoadMoreListener{
    private static final String TAG = "AreaTaskActivity";
    private PullLoadMoreRecyclerView mPullLoadMoreRecyclerView;
    private int mCount = 1;
    private AreaTaskAdapter areaTaskAdapter;
    private RecyclerView mRecyclerView;
    private LinearLayout top_bar_linear_back;
    private TextView top_bar_title;
    private RelativeLayout foot_count;
    private int pageNo=1;
    private int count;
    private SearchEditText search;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_area_task);
       // AppManager.getAppManager().addActivity(this);
        top_bar_linear_back = (LinearLayout)this.findViewById(R.id.top_bar_linear_back);
        top_bar_title = (TextView) this.findViewById(R.id.top_bar_title);
        top_bar_title.setText("抄表任务");
        top_bar_linear_back.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                AreaTaskActivity.this.finish();
            }
        });
        foot_count=(RelativeLayout) this.findViewById(R.id.foot_count);
        foot_count.setVisibility(View.GONE);
        mPullLoadMoreRecyclerView = (PullLoadMoreRecyclerView) findViewById(R.id.pullLoadMoreRecyclerView);
        //获取mRecyclerView对象
        mRecyclerView = mPullLoadMoreRecyclerView.getRecyclerView();
        //代码设置scrollbar无效？未解决！
        mRecyclerView.setVerticalScrollBarEnabled(true);
        //设置是否可以下拉刷新
        //mPullLoadMoreRecyclerView.setPullRefreshEnable(true);
        //设置是否可以上拉刷新
        //mPullLoadMoreRecyclerView.setPushRefreshEnable(false);
        //显示下拉刷新
        mPullLoadMoreRecyclerView.setRefreshing(true);
        //设置上拉刷新文字
        mPullLoadMoreRecyclerView.setFooterViewText("加载中");
        //设置上拉刷新文字颜色
        //mPullLoadMoreRecyclerView.setFooterViewTextColor(R.color.white);
        //设置加载更多背景色
        //mPullLoadMoreRecyclerView.setFooterViewBackgroundColor(R.color.colorBackground);
        mPullLoadMoreRecyclerView.setLinearLayout();

        mPullLoadMoreRecyclerView.setOnPullLoadMoreListener(this);
        areaTaskAdapter = new AreaTaskAdapter(AreaTaskActivity.this);
        areaTaskAdapter.setItemClickListener(new AreaTaskAdapter.ItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                AreaTask at = areaTaskAdapter.getDataList().get(position);
                Intent intent = new Intent(AreaTaskActivity.this, WaterUserListActivity.class);
                intent.putExtra("areaName", at.getName());
                intent.putExtra("areaCode", at.getCode());
                startActivity(intent);
                //Toast.makeText(AreaTaskActivity.this,at.getName(),Toast.LENGTH_SHORT).show();
            }
        });
        mPullLoadMoreRecyclerView.setAdapter(areaTaskAdapter);
        search = (SearchEditText) findViewById(R.id.query);

        search.setOnSearchClickListener(new SearchEditText.OnSearchClickListener() {
            @Override
            public void onSearchClick(View view) {
                onRefresh();
            }
        });
        getData();
    }

    private void getData() {
       /* new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                AreaTaskActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        areaTaskAdapter.addAllData(setList());
                        mPullLoadMoreRecyclerView.setPullLoadMoreCompleted();
                    }
                });

            }
        }, 1000);*/
        String value = search.getText().toString().trim();
        OkGo.<Page<List<AreaTask>>>get(Urls.GET_AREATASK_URL)
                .tag(this)
                .params("pageNo",pageNo)
                .params("name",value)
                .execute(new JsonCallback<Page<List<AreaTask>>>() {
                    @Override
                    public void onError(Response<Page<List<AreaTask>>> response) {

                        Throwable throwable=response.getException();
                        Log.d(TAG, "onError: "+throwable.getMessage());
                        throwable.printStackTrace();
                        Intent intent = new Intent(AreaTaskActivity.this, LoginActivity.class);
                        intent.putExtra("relogin",true);
                        startActivity(intent);
                        //super.onError(response);
                    }

                    @Override
                    public void onSuccess(Response<Page<List<AreaTask>>> response) {
                        StringBuilder sb;
                        Call call = response.getRawCall();
                        if (call != null) {
                            Log.d(TAG,"请求成功  请求方式：" + call.request().method() + "\n" + "url：" + call.request().url());
                        }
                        Log.d(TAG, "onSuccess: " +response.body());
                        Page<List<AreaTask>> page = response.body();

                        List<AreaTask> list=page.getList();
                        if(list==null){
                            return ;
                        }
                        areaTaskAdapter.addAllData(list);
                        mPullLoadMoreRecyclerView.setPullLoadMoreCompleted();
                        if(areaTaskAdapter.getItemCount()==page.getCount()){
                            mPullLoadMoreRecyclerView.setPushRefreshEnable(false);
                            mPullLoadMoreRecyclerView.setFooterViewText("没有更多啦");
                        }else{

                            pageNo += 1;
                        }
                        foot_count.setVisibility(View.VISIBLE);
                        Map<String, Object> extrData = page.getExtraData();
                        ((TextView)foot_count.findViewById(R.id.total)).setText((String)extrData.get("totalNum"));
                        ((TextView)foot_count.findViewById(R.id.doneNum)).setText((String)extrData.get("doneNum"));
                        ((TextView)foot_count.findViewById(R.id.todoNum)).setText((String)extrData.get("todoNum"));
                    }
                });

    }

    public void clearData() {
        areaTaskAdapter.clearData();
        areaTaskAdapter.notifyDataSetChanged();
    }


    private List<AreaTask> setList() {
        List<AreaTask> dataList = new ArrayList<>();
        int start = 20 * (mCount - 1);
        for (int i = start; i < 20 * mCount; i++) {
            dataList.add(new AreaTask(i+"","code"+i,"name"+i,i,i));
        }
        return dataList;

    }

    @Override
    public void onRefresh() {
        Log.e("wxl", "onRefresh");
        setRefresh();
        getData();
    }

    @Override
    public void onLoadMore() {
        Log.e("wxl", "onLoadMore");
        mCount = mCount + 1;
        getData();
    }

    private void setRefresh() {
        areaTaskAdapter.clearData();
        mCount = 1;
        pageNo=1;
        mPullLoadMoreRecyclerView.setPushRefreshEnable(true);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
       // AppManager.getAppManager().finishActivity();
        OkGo.getInstance().cancelTag(this);
    }
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideKeyboard(v, ev)) {
                hideKeyboard(v.getWindowToken());
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时则不能隐藏
     *
     * @param v
     * @param event
     * @return
     */
    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0],
                    top = l[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击EditText的事件，忽略它。
                return false;
            } else {
                v.clearFocus();
                return true;
            }
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditText上，和用户用轨迹球选择其他的焦点
        return false;
    }

    /**
     * 获取InputMethodManager，隐藏软键盘
     *
     * @param token
     */
    private void hideKeyboard(IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }
}
